<template>
  <!-- 系统目录 西成药品 -->
  <div class="MedicenCata">
    <div class="dialog">

      <!--患者选择-->
      <el-dialog
          title="患者选择"
          :close-on-click-modal="false"
          :visible.sync="patientDialogVisible"
          width="70%"
          class="patient-dialog optimized-dialog"
      >
        <!-- 患者表格 -->
        <el-table
            :data="patientTableData"
            border
            highlight-current-row
            @current-change="handleClickRow"
            style="width: 100%"
            height="500px"
        >
          <el-table-column v-for="(col, inx) in tableRows4" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" :render-header="labelHead" align="center"
                           :min-width="getColumnWidth(col.label,col.prop,patientTableData)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row) }}
            </template>
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="patientDialogVisible = false" size="mini" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleChoosePatient" size="mini" :loading="loading" class="confirm-btn">
            确定
          </el-button>
        </div>

      </el-dialog>

      <!--待收费病人列表-->
      <el-dialog
          title="待收费病人列表"
          :close-on-click-modal="false"
          :visible.sync="awaitingPayDialogVisible"
          width="85%"
          class="patient-dialog optimized-dialog"
          :class="{'with-details': showAwaitingPayDetail}">

        <div class="table-main-container" :class="{'with-drawer': showAwaitingPayDetail}">
          <!-- 左侧主表格 -->
          <div class="table-left">
            <el-table
                :data="tableData4"
                border
                height="60vh"
                highlight-current-row
                show-summary
                :summary-method="getSummaries2"
                @current-change="getAwaitPayDetail"
                @row-dblclick="getOutPatientCharge"
            >
              <el-table-column fixed="left" label="行号" type="index" width="50px" align="center"></el-table-column>
              <el-table-column v-for="(col, inx) in tableRows5" :key="inx" :type="col.type" :prop="col.prop"
                               :label="col.name" :render-header="labelHead" align="center"
                               :width="{'createTime': '200px','westernDiagnos': '300px','chinaDiagnose':'300px'}[col.prop] || undefined"
                               :min-width="getColumnWidth(col.label,col.prop,tableData4)">
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  width="100"
                  align="center"
                  fixed="right"
              >
                <template #default="{ row }">
                  <el-button
                      type="primary"
                      size="mini"
                      @click.stop="getOutPatientCharge(row)"
                  >选择
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 右侧抽屉式表格 (收费明细) -->
          <div class="table-drawer" :class="{'open': showAwaitingPayDetail}">
            <div class="drawer-content">
              <el-table
                  ref="payDetailTable"
                  :data="tableData5"
                  border
                  show-summary
                  :summary-method="getSummaries2"
                  height="60vh"
                  class="custom-summary-table"
                  style="width: 100%">
                <el-table-column fixed="left" label="行号" type="index" width="50px" align="center"></el-table-column>
                <el-table-column v-for="(col, inx) in tableRows6" :key="inx" :type="col.type" :prop="col.prop"
                                 :label="col.name" align="center" :render-header="labelHead"
                                 :min-width="getColumnWidth(col.label,col.prop,tableData5)">
                  <template #default="{ row }">
                    {{ safeGetMappedValue(col, row) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-checkbox v-model="showAwaitingPayDetail" size="mini" style="margin-right: 20px;">显示收费明细</el-checkbox>
          <el-button @click="awaitingPayDialogVisible = false" size="mini" class="cancel-btn">取消</el-button>
        </div>
      </el-dialog>

      <!--快速建档-->
      <el-dialog
          title="快速建档-新增健康档案"
          :close-on-click-modal="false"
          :visible.sync="celerityFilingDialogVisible"
          width="50%"
          class="patient-dialog"
      >
        <el-form :model="celerityFilingForm" label-width="90px" size="mini" class="compact-form">
          <!-- 第一行：基本信息 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名:">
                <el-input v-model="celerityFilingForm.name" size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别:">
                <el-select v-model="celerityFilingForm.sex" size="mini" style="width: 70px">
                  <el-option label="男" value="1"></el-option>
                  <el-option label="女" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证件类型:">
                <el-select v-model="celerityFilingForm.identityCard" size="mini" style="width: 100%" filterable
                           clearable>
                  <el-option v-for="item in certypeOption" :key="item.id" :label="item.label"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：证件号码和出生日期 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证件号码:">
                <el-input
                    v-model="celerityFilingForm.certno"
                    style="width: 100%"
                    @blur="certnoMonitor(celerityFilingForm)"
                    @clear="patientForm.ageYear = null;patientForm.ageMonth = null;patientForm.brdy = '';"
                    clearable
                    maxlength="18"
                    show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期:">
                <el-date-picker
                    v-model="celerityFilingForm.brdy"
                    type="date"
                    size="mini"
                    style="width: 100%"
                    :disabled="true"
                    :placeholder="patientForm.certno ? '' : '身份证自动计算'"
                    value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第三行：国家、民族、职业 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="国籍:">
                <el-select v-model="celerityFilingForm.ntlyId" size="mini" style="width: 100%" filterable clearable>
                  <el-option v-for="item in ntlyOptions" :key="item.id" :label="item.label"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="民族:">
                <el-select v-model="celerityFilingForm.naty" size="mini" style="width: 100%" filterable clearable>
                  <el-option v-for="item in nationOption" :key="item.id" :label="item.label"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业:">
                <el-select v-model="celerityFilingForm.jobId" size="mini" style="width: 100%" filterable clearable>
                  <el-option v-for="item in profttlOption" :key="item.id" :label="item.label"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第四行：病员类型和合约单位 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="病员类型:">
                <el-select v-model="celerityFilingForm.prhType" size="mini" style="width: 100%">
                  <el-option v-for="item in this.prhTypeOption" :key="item.id" :label="item.label" :value="item.id">
                    <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合约单位:">
                <el-select
                    v-model="celerityFilingForm.contractUnit"
                    size="mini"
                    style="width: 100%"
                    filterable
                    clearable
                    @focus="getContuntList"
                >
                  <el-option v-for="item in contractUnitOption" :key="item.id" :label="item.label" :value="item.id">
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right">
                <el-button size="mini" type="primary" plain @click.stop="handleEditContractUnit(item)"
                           style="margin-left: 10px">
                  保存
                </el-button>
                <el-tooltip content="若查询信息不对,可重新填写后点此按钮更改" placement="top" style="margin-left: 8px;">
                  <i class="el-icon-question" style="color: #909399; cursor: pointer;"></i>
                </el-tooltip>
              </span>
                  </el-option>
                  <el-option :value="undefined" disabled style="cursor: pointer">
                    <el-button type="text" @click="addUnitModalVisible = true">
                      <i class="el-icon-plus" style="font-weight: bold"></i> 新增合约单位
                    </el-button>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第五行：联系人信息 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系人:">
                <el-input v-model="celerityFilingForm.conerName" size="mini" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:">
                <el-input v-model="celerityFilingForm.conerTel" size="mini" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人关系:">
                <el-select v-model="celerityFilingForm.conerRltsId" size="mini" style="width: 100%" filterable
                           clearable>
                  <el-option v-for="item in this.rltsEntitiesOption" :key="item.id" :label="item.label"
                             :value="item.id">
                    <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第六行：联系地址（单独一行） -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="联系地址:">
                <div class="address-container">
                  <el-select v-model="celerityFilingForm.province" @clear="handleClear(1)" size="mini"
                             style="width: 15%;" @focus="getArea()" filterable clearable>
                    <el-option v-for="item in this.provinces" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                  <span class="address-unit">省</span>

                  <el-select v-model="celerityFilingForm.city" size="mini"
                             style="width: 15%;" @focus="getCity" @clear="handleClear(2)" filterable clearable
                             :disabled="celerityFilingForm.province===''">
                    <el-option v-for="item in this.cityOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                  <span class="address-unit">市</span>

                  <el-select v-model="celerityFilingForm.county" size="mini" @clear="handleClear(3)" style="width: 15%;"
                             @focus="getCounty" filterable clearable :disabled="celerityFilingForm.city === ''">
                    <el-option v-for="item in this.countyOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                  <span class="address-unit">县</span>

                  <el-select v-model="celerityFilingForm.town" size="mini" @clear="handleClear(4)" style="width: 15%;"
                             @focus="getTown" filterable clearable :disabled="celerityFilingForm.county === ''">
                    <el-option v-for="item in this.townOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                  <span class="address-unit">镇</span>

                  <el-select v-model="celerityFilingForm.village" size="mini" @clear="handleClear(5)"
                             style="width: 20%;"
                             @focus="getVillage" filterable clearable :disabled="celerityFilingForm.town === ''">
                    <el-option v-for="item in this.villageOption" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                    </el-option>
                  </el-select>
                  <span class="address-unit">乡</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="celerityFilingDialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="handleAddCelerityFiling" size="mini" :loading="loading">保存</el-button>
        </div>
      </el-dialog>

      <!--结算-->
      <el-dialog
          title="门诊支付窗口"
          :close-on-click-modal="false"
          :visible.sync="settleAccountsDialogVisible"
          width="800px"
          class="payment-dialog"
      >
        <el-form :model="paymentForm" label-width="100px" class="payment-form">
          <!-- 上半部分：金额信息 -->
          <div class="form-section">
            <!-- 第一排：3个字段 -->
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="应收金额:">
                  <el-input size="mini" v-model="outpatientChargesForm.currentTotal" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="当前票号:">
                  <el-input size="mini" v-model="outpatientChargesForm.currentTicketNo" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="账户余额:">
                  <el-input size="mini" v-model="paymentForm.balance" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二排：2个字段 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="挂账余额:">
                  <el-input size="mini" v-model="paymentForm.credit" value="0/0" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="留观金额:">
                  <el-input size="mini" v-model="paymentForm.observation" value="0" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 备注单独一行 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:">
                  <el-input size="mini" type="textarea" v-model="paymentForm.remarks"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="form-section">
            <!-- 第一行：病员费别 + 现金支付 + 医保支付 -->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="病人费别:" class="payment-item">
                  <el-select size="mini" v-model="outpatientChargesForm.patientType"
                             clearable>
                    <el-option v-for="item in prhTypeOption" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="现金支付:" class="payment-item">
                  <el-input type="number" min="0" size="mini" v-model="paymentForm.cashAmt" @input="calculatePayments"
                            value="45.80"
                            :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="医保支付:" class="payment-item">
                  <el-input type="number" min="0" :disabled="true" size="mini" @input="calculatePayments"
                            v-model="paymentForm.chsAmt"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：健康卡付 + 银联支付 + 优惠金额 -->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="健康卡付:" class="payment-item">
                  <el-input type="number" min="0" size="mini" v-model="paymentForm.patAmt" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="银联支付:" class="payment-item">
                  <el-input type="number" min="0" size="mini" :disabled="true" @input="calculatePayments"
                            v-model="paymentForm.bankAmt"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="优惠金额:" class="payment-item">
                  <el-input type="number" min="0" size="mini" :disabled="true" @input="calculatePayments"
                            v-model="paymentForm.distAmt"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行：挂账支付 + 网络支付 + 留观预交  payTypeOption-->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="挂账支付:" class="payment-item">
                  <el-input type="number" min="0" size="mini" @input="calculatePayments"
                            v-model="paymentForm.bebtAmt"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item class="payment-item" label="网络支付:">
                  <!-- 替换 label 的下拉框 -->
                  <!--                  <el-select
                                        v-model="paymentForm.opeWay"
                                        size="mini"
                                        clearable
                                        placeholder="支付方式"
                                        style="width: 83px; margin-left: -83px"
                                    >
                                      <el-option
                                          v-for="item in payTypeOption"
                                          :key="item.id"
                                          :label="item.label"
                                          :value="item.id"
                                      />
                                    </el-select>-->

                  <!-- 原来的输入框 -->
                  <el-input min="0" type="number" size="mini" v-model="paymentForm.groupAmt"
                            @input="calculatePayments"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="留观预交:" class="payment-item">
                  <el-input size="mini" v-model="paymentForm.observationAdvance" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 结算信息 -->
            <div class="payment-summary">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="应付金额:" class="compact-item">
                    <span class="amount">{{ outpatientChargesForm.currentTotal }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收到金额:" class="compact-item">
                    <el-input @input="calculatePayments" ref="recdAmt" size="mini" v-model="paymentForm.recdAmt"
                              class="compact-input"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="应退找零金额:" class="compact-item">
                    <span class="amount">{{ paymentForm.change }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 按钮组 -->
          <div class="form-actions">
            <el-button type="text">查看优惠明细</el-button>
            <el-button>打印发票</el-button>
            <el-button type="primary" @click="handleConfirmPayment">确认支付</el-button>
            <el-button type="warning" @click="handleClosePayment">退出支付</el-button>
          </div>
        </el-form>
      </el-dialog>

      <!--选择挂账类型-->
      <el-dialog
          title="请选择挂账类型"
          :close-on-click-modal="false"
          :visible.sync="onCreditDialogVisible"
          width="30%"
      >
        <!-- 下拉框 -->
        <el-select
            v-model="paymentForm.bebtId"
            placeholder="请选择选项"
            style="width: 100%"
            size="mini"
        >
          <el-option v-for="item in onCreditOption" :key="item.id" :label="item.label" :value="item.id">
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right" v-if="permissionsArr?.includes('system:bebttype:edit')">
              <el-button size="mini" type="primary" plain @click.stop="handleOpenEditOnCredit(item)"
                         style="margin-left: 10px">
                修改
              </el-button>
              </span>
          </el-option>
          <el-option :value="undefined" disabled style="cursor: pointer"  v-if="permissionsArr?.includes('system:bebttype:add')"><!--system:bebttype:add-->
            <el-button type="text" @click="handleOpenAddOnCredit"><i class="el-icon-plus"
                                                                     style="font-weight: bold"></i> 新增挂账类型
            </el-button>
          </el-option>
        </el-select>

        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="handleCloseOnCredit" size="mini">取消</el-button>
        <el-button type="primary" @click="handleConfirmPayment2" size="mini">确认</el-button>
      </span>
      </el-dialog>


      <el-dialog :title="addUnitForm.id  == null ?'新增合约单位':'修改合约单位'" :before-close="handleCancelAddUnit"
                 :visible.sync="addUnitModalVisible" class="addUnitDialog" width="50%" :close-on-click-modal="false">
        <div class="aform">
          <!-- 表单 -->
          <el-form :model="addForm" label-width="90px" size="mini" :rules="addUnitRules" ref="addUnitRef">
            <el-row :gutter="20">
              <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addUnitType" :key="i"
                      :style="{ marginLeft: v.modelValue === 'uscc' ? '18px' : '0' }">
                <!-- input -->
                <el-form-item v-if="v.type === 'input'" :required="['code', 'name'].includes(v.modelValue)"
                              :label="v.label" :style="v.modelValue === 'uscc' ? 'white-space: nowrap' : ''">
                  <el-input :suffix-icon='v.prefix' v-model="$data.addUnitForm[v.modelValue]"
                            @input="handleNameChangeCode(v,i)"
                            :style="{ marginLeft: v.modelValue === 'uscc' ? '30px' : '0' }">

                  </el-input>
                </el-form-item>
                <!-- select -->
                <el-form-item v-if="v.type === 'select'" :label="v.label">
                  <el-select v-model="$data.addUnitForm[v.modelValue]" filterable
                             :disabled="v.modelValue === 'untAtte'">
                    <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAddContractUnit">
                {{ addUnitForm.id == null ? '新增' : '修改' }}
              </el-button>
              <el-button size="mini" @click="handleCancelAddUnit" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>
      <!--新增修改挂账类型-->
      <el-dialog
          :title='addOnCreditForm.id == null ? "新增挂账类型" : "修改挂账类型"'
          :close-on-click-modal="false"
          :visible.sync="addOnCreditDialogVisible"
          width="700px"
          @close="handleCloseAddOnCredit"
          class="custom-form-dialog"
      >
        <el-form
            size="mini"
            :model="addOnCreditForm"
            ref="addOnCreditForm"
            :rules="addOnCreditFormRules"
            label-width="110px"
            label-position="right"
        >
          <!-- 第一行：编码 + 合约单位 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="编码：" prop="code">
                <el-input
                    v-model="addOnCreditForm.code"
                    placeholder="如：HT20230001"
                    clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合约单位：" prop="cotUnit">
                <el-select
                    v-model="addOnCreditForm.cotUnit"
                    placeholder="请选择"
                    style="width: 100%"
                    clearable
                >
                  <el-option :value="undefined" disabled style="cursor: pointer">
                    <el-button type="text" @click="handleSaveContractUnit" style="padding: 0;">
                      <i class="el-icon-plus" style="font-weight: bold"></i> 新增合约单位
                    </el-button>
                  </el-option>
                  <el-option v-for="item in contractUnitOption" :key="item.id" :label="item.label"
                             :value="item.id">
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right">
                    <el-button size="mini" type="primary" plain @click.stop="handleEditContractUnit(item)"
                               style="margin-left: 6px; padding: 4px;">修改</el-button>
                  </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：名称 + 状态 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="名称：" prop="name">
                <el-input
                    v-model="addOnCreditForm.name"
                    @input="handleOnCreditNameGetPy"
                    placeholder="请输入完整名称"
                    clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态：" prop="state">
                <el-select
                    v-model="addOnCreditForm.state"
                    placeholder="请选择状态"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in stateOption"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 第三行：开始时间 + 结束时间 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间：" prop="beginTime">
                <el-date-picker
                    v-model="addOnCreditForm.beginTime"
                    type="datetime"
                    placeholder="选择开始时间"
                    style="width: 100%"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="'00:00:00'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间：" prop="endTime">
                <el-date-picker
                    v-model="addOnCreditForm.endTime"
                    type="datetime"
                    placeholder="选择结束时间"
                    style="width: 100%"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="'23:59:59'"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 拼音简码（单独一行） -->
          <el-form-item label="拼音简码：">
            <el-input
                v-model="addOnCreditForm.pycode"
                placeholder="自动生成"
                disabled
                class="disabled-input"
            />
          </el-form-item>


          <!-- 备注（文本域） -->
          <el-form-item label="备注：">
            <el-input
                type="textarea"
                v-model="addOnCreditForm.remarks"
                :rows="3"
                placeholder="可输入额外说明信息"
                resize="none"
                show-word-limit
                maxlength="200"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCloseAddOnCredit" size="mini">取消</el-button>
          <el-button type="primary" @click="handleAddOnCredit" size="mini">保存</el-button>
        </div>
      </el-dialog>

      <!--新增修改合约单位-->
      <el-dialog :title="addUnitForm.id  == null ?'新增合约单位':'修改合约单位'" :before-close="handleCancelContract"
                 :visible.sync="addUnitModalVisible" class="addUnitDialog" width="50%" :close-on-click-modal="false">
        <div class="aform">
          <!-- 表单 -->
          <el-form label-width="90px" size="mini" :rules="addUnitRules" ref="addUnitRef">
            <el-row :gutter="20">
              <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addUnitType" :key="i"
                      :style="{ marginLeft: v.modelValue === 'uscc' ? '18px' : '0' }">
                <!-- input -->
                <el-form-item v-if="v.type === 'input'" :required="['code', 'name'].includes(v.modelValue)"
                              :label="v.label" :style="v.modelValue === 'uscc' ? 'white-space: nowrap' : ''">
                  <el-input :suffix-icon='v.prefix' v-model="$data.addUnitForm[v.modelValue]"
                            @input="handleNameChangeCode(v,i)"
                            :disabled="v.disabled"
                            :style="{ marginLeft: v.modelValue === 'uscc' ? '30px' : '0' }">

                  </el-input>
                </el-form-item>
                <!-- select -->
                <el-form-item v-if="v.type === 'select'" :label="v.label">
                  <el-select v-model="$data.addUnitForm[v.modelValue]" filterable
                             :disabled="v.modelValue === 'untAtte'">
                    <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAddContractUnit">
                {{ addUnitForm.id == null ? '新增' : '修改' }}
              </el-button>
              <el-button size="mini" @click="handleCancelContract" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>

      <!--付款码支付窗口-->
      <el-dialog
          title="请扫描患者付款码"
          :visible.sync="payModalVisible"
          width="30%"
          :close-on-click-modal="false"
          @opened="handlePayDialogOpened"
          @closed="handlePayDialogClosed">

        <!-- 隐藏的扫码输入框 -->
        <div style="position: absolute; left: -9999px;">
          <el-input
              ref="paymentCodeInput"
              v-model="paymentCode"
              @input="handleScanComplete">
          </el-input>
        </div>

        <!-- 可视化提示区域 -->
        <div style="text-align: center; padding: 20px 0;">
          <!-- 状态1：等待扫码 -->
          <template v-if="scanStatus === 'waiting'">
            <i class="el-icon-loading" style="font-size: 40px;"></i>
            <p style="margin-top: 15px;">请使用扫码枪扫描顾客付款码</p>
          </template>

          <!-- 状态2：处理中 -->
          <template v-else-if="scanStatus === 'processing'">
            <i class="el-icon-loading" style="font-size: 40px;"></i>
            <p style="margin-top: 15px;">正在处理付款请求...</p>
          </template>

          <!-- 状态3：处理成功 -->
          <template v-else-if="scanStatus === 'success'">
            <i class="el-icon-success" style="font-size: 40px; color: #67C23A;"></i>
            <p style="margin-top: 15px;">
              付款成功！{{ countdown }}秒后自动关闭
            </p>
            <el-progress
                :percentage="countdown * 20"
                status="success"
                style="width: 80%; margin: 10px auto;"
            ></el-progress>
          </template>

          <template v-else-if="scanStatus === 'error'">
            <i class="el-icon-error" style="font-size: 40px; color: #F56C6C;"></i>
            <p style="margin-top: 15px;">{{ errorMessage }}</p>
            <p style="margin-top: 10px; color: #999;">{{ countdown }}秒后重新开始扫码</p>
            <el-progress
                :percentage="countdown * 20"
                status="exception"
                style="width: 80%; margin: 10px auto;"
            ></el-progress>
          </template>
        </div>
      </el-dialog>

      <!--结班-->
      <el-dialog
          :close-on-click-modal="false"
          title="结班"
          :visible.sync="finalReportDialogVisible"
          width="80%"
          @close="handleCloseFinalReport">
        <el-form
            :model="finalReportShowFrom"
            size="mini"
            label-width="100px">
          <el-row :gutter="0">
            <el-col :span="4">
              <el-form-item label="机构:">
                <el-input v-model="finalReportShowFrom.clinicName" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="结班人:">
                <el-input v-model="finalReportShowFrom.staffName" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统计时间：">
                <!-- 使用统一的日期范围选择器 -->
                <el-date-picker
                    v-model="finalReportShowFrom.timeRange"
                    type="datetimerange"
                    range-separator="-"
                    :default-time="defaultTimeRange"
                    style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button
                  type="primary"
                  size="mini"
                  style="margin-top: 2px;">
                统计
              </el-button>
            </el-col>
          </el-row :gutter="0">
        </el-form>

        <!-- 其他内容保持不变 -->
        <el-tabs type="border-card" style="height: 100%" v-model="activeTab" @tab-click="handleTabClick" >
          <el-tab-pane label="结班信息" name="classInfo"></el-tab-pane>
          <el-tab-pane label="收费信息" name="paymentInfo">
            <el-table :data="tableData7" border highlight-current-row>
              <el-table-column v-for="(col, inx) in tableRows8" :key="inx" :type="col.type" :prop="col.prop"
                               :label="col.name" :render-header="labelHead" align="center"
                               :min-width="getColumnWidth(col.label,col.prop,tableData7)">
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
              <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleChargeListSizeChange"
                @current-change="handleChargeListCurrentChange"
                :current-page="pageNum"
                :page-sizes="[8, 16, 32]"
                :page-size="pageSize"
                :total="totalSize"
                layout="total, sizes, prev, pager, next, jumper"
                background>
            </el-pagination>
          </el-tab-pane>
          <el-tab-pane label="挂号信息" name="registrationInfo">
            <el-table :data="tableData6" border highlight-current-row height="100%">
              <el-table-column v-for="(col, inx) in tableRows7" :key="inx" :type="col.type" :prop="col.prop"
                               :label="col.name" :render-header="labelHead" align="center"
                               :min-width="getColumnWidth(col.label,col.prop,tableData6)">
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
              <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleRegistrationSizeChange"
                @current-change="handleRegistrationCurrentChange"
                :current-page="pageNum"
                :page-sizes="[8, 16, 32]"
                :page-size="pageSize"
                :total="totalSize"
                layout="total, sizes, prev, pager, next, jumper"
                background>
            </el-pagination>
          </el-tab-pane>
        </el-tabs>

        <span slot="footer" class="dialog-footer no-line">
      <el-button type="primary" size="mini">保存</el-button>
      <el-button size="mini" @click="handleCloseFinalReport">取消</el-button>
    </span>
      </el-dialog>
    </div>
    <el-tabs type="border-card">
      <el-tab-pane label="患者信息">
        <el-form :model="outpatientChargesForm" label-width="90px" size="mini" class="compact-form">
          <!-- 使用grid布局 -->
          <div style="display: grid; grid-template-columns: 1fr 180px; gap: 20px;">
            <!-- 左侧主内容区 -->
            <div>
              <!-- 第一行 - 6个表单项 -->
              <el-row :gutter="4" style="margin-bottom: 25px;">
                <!-- 每个 el-col 增加 padding-left 和 padding-right -->
                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="健康ID:">
                    <el-input v-model="outpatientChargesForm.patId" size="mini"
                              @keyup.enter.native="handleSearch">
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="姓名:">
                    <el-input v-model="outpatientChargesForm.name" :disabled="true" size="mini"/>
                  </el-form-item>
                </el-col>

                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="年龄:">
                    <el-input v-model="outpatientChargesForm.age" :disabled="true" size="mini"/>
                  </el-form-item>
                </el-col>

                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="开单医生:">
                    <el-select size="mini" v-model="outpatientChargesForm.billingDoctor"
                               clearable :disabled="true">
                      <el-option v-for="item in userOptions" :key="item.id" :label="item.username"
                                 :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="开单科室:">
                    <el-select size="mini" v-model="outpatientChargesForm.billingDept"
                               clearable :disabled="true">
                      <el-option v-for="item in deptOptions" :key="item.id" :label="item.label"
                                 :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                  <el-form-item label="病人类型:">
                    <el-select size="mini" v-model="outpatientChargesForm.patientType"
                               clearable disabled>
                      <el-option v-for="item in prhTypeOption" :key="item.id" :label="item.label"
                                 :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <!--              <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                                <el-form-item label="余额:">
                                  <el-input v-model="outpatientChargesForm.remainingSum" :disabled="true" size="mini"/>
                                </el-form-item>
                              </el-col>-->
              </el-row>

              <!-- 第二行 - 收费项目等 -->
              <!--            <el-row :gutter="10">
                            <el-col :span="7" style="padding-left: 15px; padding-right: 15px;">
                              <el-form-item label="收费项目:">
                                <el-select size="mini" v-model="outpatientChargesForm.chargeItem"
                                           clearable style="width: 250px">
                                  <el-option v-for="item in chargingPriceOptions" :key="item.id" :label="item.label"
                                             :value="item.id"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>

                            <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                              <el-form-item label="规格:">
                                <el-input v-model="outpatientChargesForm.specification" :disabled="true" size="mini"/>
                              </el-form-item>
                            </el-col>

                            <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                              <el-form-item label="执行科室:">
                                <el-select size="mini" v-model="outpatientChargesForm.executeDept"
                                           clearable>
                                  <el-option v-for="item in deptOptions" :key="item.id" :label="item.label"
                                             :value="item.id"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>

                            <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                              <el-form-item label="单价:">
                                <el-input v-model="outpatientChargesForm.price" :disabled="true" size="mini"/>
                              </el-form-item>
                            </el-col>

                            <el-col :span="4" style="padding-left: 15px; padding-right: 15px;">
                              <el-form-item label="数量:">
                                <el-input v-model="outpatientChargesForm.amount" :disabled="true" size="mini"/>
                              </el-form-item>
                            </el-col>


                          </el-row>-->
            </div>

            <!-- 右侧票据信息（保持不变）  billTypeOption-->
            <!--          <div style="display: flex; flex-direction: column; justify-content: space-between;margin-left:10px">
                        <el-form-item label="票据类型:" label-width="90px" style="margin-top: 4px;">
                          <el-select size="mini" v-model="outpatientChargesForm.ticketType" style="width: 120px">
                            <el-option v-for="item in ticketTypeOption" :key="item.id" :label="item.label"
                                       :value="item.id"></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="当前票号:" label-width="90px" style="margin-bottom: 4px;">
                          <el-input v-model="outpatientChargesForm.currentTicketNo" :disabled="true" size="mini"/>
                        </el-form-item>
                      </div>-->
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
<!--    <div class="compact-form-box" style="height: 220px">

    </div>-->

    <el-tabs type="border-card">
      <el-tab-pane label="收费信息">
        <div class="medical-system-container">
          <!-- 1. 主表格区域 -->
          <div class="table-main-container" :class="{'with-drawer': showDetails}">
            <!-- 左侧主表格 -->
            <div class="table-left">
              <el-table
                  :data="tableData1"
                  border
                  height="100%"
                  @row-click="handleCurrentRow"
                  highlight-current-row>
                <el-table-column fixed="left" label="行号" type="index" width="50px" align="center"></el-table-column>
                <el-table-column v-for="(col, inx) in tableRows1" :key="inx" :type="col.type" :prop="col.prop"
                                 :label="col.name" :render-header="labelHead" align="center"
                                 :min-width="getColumnWidth(col.label,col.prop,tableData1)">
                  <template #default="{ row }">
                    {{ safeGetMappedValue(col, row) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 右侧抽屉式表格 -->
            <div class="table-drawer" :class="{'open': showDetails}">
              <div class="drawer-content">
                <el-table
                    v-if="(currentRowData?.orderType === 0 && hasInitTable0)"
                    ref="rightTable"
                    :data="tableData2"
                    border
                    height="100%"
                    style="width: 100%">
                  <el-table-column fixed="left" label="行号" type="index" width="50px" align="center"></el-table-column>
                  <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop"
                                   :label="col.name" :render-header="labelHead" align="center"
                                   :min-width="getColumnWidth(col.label,col.prop,tableData2)">
                    <template #default="{ row }">
                      {{ safeGetMappedValue(col, row) }}
                    </template>
                  </el-table-column>
                </el-table>

                <el-table
                    v-else-if="(currentRowData?.orderType === 1 && hasInitTable1)"
                    ref="rightTable"
                    :data="tableData3"
                    border
                    show-summary
                    :summary-method="getSummaries"
                    height="55vh"
                    class="custom-summary-table"
                    style="width: 100%">
                  <el-table-column fixed="left" label="行号" type="index" width="50px" align="center"></el-table-column>
                  <el-table-column v-for="(col, inx) in tableRows3" :key="inx" :type="col.type" :prop="col.prop"
                                   :label="col.name" :render-header="labelHead" align="center"
                                   :min-width="getColumnWidth(col.label,col.prop,tableData4)">
                    <template #default="{ row }">
                      {{ safeGetMappedValue(col, row) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>

          <!-- 2. 底部控制表单（严格保持在底部） -->
            <el-form :model="patientForm" label-width="90px" size="mini">
              <div class="form-grid">
                <div class="form-main">
                  <el-row :gutter="10">
                    <el-col :span="3">
                      <el-form-item label="本次合计:">
                        <el-input disabled v-model="outpatientChargesForm.currentTotal"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="折后合计:">
                        <el-input v-model="outpatientChargesForm.discountedTotal" :disabled="true"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="上一健康ID:">
                        <el-input v-model="outpatientChargesForm.BeforePatId" :disabled="true"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="上笔金额:">
                        <el-input v-model="outpatientChargesForm.BeforePaidAmt" :disabled="true"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="上笔收到:">
                        <el-input v-model="outpatientChargesForm.BeforeReceiveAmt" :disabled="true"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="上笔找零:">
                        <el-input v-model="outpatientChargesForm.BeforeChange" :disabled="true"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item label="显示明细:" label-width="80px">
                        <el-checkbox v-model="showDetails"/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <div class="button-group">
                    <!-- 前三个按钮紧挨着 -->
                    <div class="primary-actions">
                      <el-button type="primary" size="mini" @click="handleOpenFinalReport">结班</el-button>
                      <!-- <el-button type="primary" size="small">票据管理</el-button>
                      <el-button type="primary" size="small" @click="celerityFilingDialogVisible = true">快速建档</el-button>-->
                    </div>

                    <!-- 操作按钮组  -->
                    <div class="action-buttons">
                      <!--                <el-button type="warning" size="small" @click="getSqbPaymentState">修改</el-button>-->
                      <el-button type="primary" size="mini" @click="loadData">待收费列表</el-button>
                      <el-button type="danger" size="mini" @click="handleCancelCurrentRow">移除</el-button>
                      <el-button type="warning" size="mini" @click="handleCancelCurrentPatient">重建</el-button>
                      <el-button type="success" size="mini" @click="handleSettleAccounts">结算</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>

import {
  addContractUnit,
  addDocphr,
  dict,
  editContractUnit,
  getArea,
  getContractUnit,
  getContuntList,
  getDeptList,
  getDocphrList,
  getDoctorList
} from "@/api/reservation/reservation";
import AddType from './reservationAddType.js'
import {pinyin} from "pinyin-pro";
import {getChargingPrice} from "@/api/cosrute/Cosrute";
import {
  addConfirmPayment,
  addOnCredit,
  editOnCredit,
  getChargelist,
  getChinaDetail,
  getOnCreditById,
  getOnCreditList,
  getSqbPaymentState,
  getWestDetail,
  sqbPayment
} from "@/api/reservation/outpatientCharge";
import {getMedicationFrequency} from "@/api/reservation/outpatientPhysician";
import {getDosaUnt} from "@/api/MedicenCata";
import {MessageBox} from 'element-ui';
import {readIdCard} from "@/untils/idCardReader";
import {withLoading} from "@/untils/loading";
import {getuserInfo} from "@/api/user";
import dayjs from "dayjs";
import {getAllReservation, getRegisterType} from "@/api/reservation/reservationList";
import {getChargeList} from "@/api/reservation/outpatientChargeList";

export default {
  components: {},
  data() {
    return {
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      //控制变量
      showDetails: false,//表格明细
      patientDialogVisible: false,//患者选择弹窗
      finalReportDialogVisible: false,//结班
      showAwaitingPayDetail: false,//待收费病人明细
      awaitingPayDialogVisible: false,//代收费病人列表
      loading: false,//加载圈
      celerityFilingDialogVisible: false,//快速建档弹窗
      settleAccountsDialogVisible: false,//门诊支付弹窗
      onCreditDialogVisible: false,//选择挂账类型弹窗
      addOnCreditDialogVisible: false,//新增挂账类型弹窗
      addUnitModalVisible: false, // 合约单位弹出框
      hasInitTable0: false, // 区分中西处方
      hasInitTable1: false, // 区分中西处方
      patientFormDisabled: false,//患者表单置灰
      payModalVisible: false,//支付弹出框
      paymentCode: '',//支付码
      terminalId: null,//系统序号
      scanTimer: null,//防抖
      isProcessing: false,//支付判断
      isSuccess: false,//支付判断
      scanStatus: 'waiting', // waiting|processing|success
      errorMessage: '付款失败,请重试', // waiting|processing|success
      resetTimer: null,
      countdown: 5, // 倒计时秒数
      countdownInterval: null, // 倒计时定时器
      orderId: 32,//回调订单ID
      countdownStartTime: 0,    // 记录倒计时开始时间
      animationFrameId: null,   // 存储动画帧ID

      //表格数据容器
      patientTableData: [],//选择患者表格
      tableData1: [],//主表格
      tableData2: [],//西药表格
      tableData3: [],//中药表格
      tableData4: [],//代收费病人列表
      tableData5: [],//代收费病人列表详情
      tableData6: [],//挂号列表
      tableData7: [],//收费列表
      currentRowData: {},//中西处方选择的当前行数据
      activeTab: 'classInfo',

      //下拉框容器
      provinces: [],  // 所有省份
      cityOption: [],     // 当前省下的城市
      countyOption: [],    // 当前市下的区县
      townOption: [],    // 区县下的乡
      villageOption: [],    // 区县下的乡
      prhCostOption: [],//病员费别
      prhTypeOption: [],//病员类别
      rltsEntitiesOption: [],//联系人关系
      contractUnitOption: [],//合约单位
      onCreditOption: [],//挂账类型
      untAtteOption: [],//往来单位新增---单位属性
      deptOptions: [],//科室下拉框
      doctorOptions: [],//医生下拉框
      chargingPriceOptions: [],//项目价格下拉框
      registerOptions: [],//挂号类别
      ntlyOptions: [],//国籍
      medicationFrequencyOptions: [],//给药方式
      dosaUntOptions: [],//单位
      addUnitType: [], //合约单位动态表单
      nationOption: [],//民族下拉框
      certypeOption: [],//证件下拉框
      profttlOption: [],//职业下拉框
      feeTypeOption: [],//病案费别下拉框
      userOptions: [],//当前登陆人用户信息
      ticketTypeOption: [{id: 1, label: '普通门诊发票'}],
      orderTypeOptions: [{id: 0, label: '西药处方费'}, {id: 1, label: '中药处方费'}, {id: 2, label: '检查费'}, {
        id: 3,
        label: '检验费'
      }, {id: 4, label: '处置项目费'}, {id: 5, label: '快速就诊费'}, {id: 6, label: '关联处置费'}],
      payTypeOption: [{id: 2, label: '支付宝'}, {id: 3, label: '微信'}],
      stateOption: [{id: 0, label: '禁用'}, {id: 1, label: '可用'}],
      sexOptions: [{id: '1', label: '男'}, {id: '2', label: '女'}],
      payTypeOptions: [{id: 1, label: '现金'}, {id: 2, label: '支付宝'}, {id: 3, label: '微信'},
        {id: 4, label: '银行卡'}, {id: 5, label: '医保'}, {id: 6, label: '优惠支付'},
        {id: 7, label: '健康卡支付'}, {id: 8, label: '聚合支付'}, {id: 9, label: '组合支付'},
      ],
      payStateOptions: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      regModeOption: [
        {id: 1, label: '窗口'}, {id: 2, label: '诊间'}, {id: 3, label: '自助'},
        {id: 4, label: '预约'}, {id: 5, label: '自动'}, {id: 6, label: '收费'},
        {id: 7, label: '微信'}, {id: 8, label: 'APP'}, {id: 9, label: '分诊'}, {id: 99, label: '体检接口使用'}
      ],
      regOptions:[],
      // 表格动态列
      tableRows1: [
        {name: "发票费别", prop: "orderType", op: 'orderTypeOptions'},
        {name: "项目名称", prop: "orderType", op: 'orderTypeOptions'},
        {name: "合计金额", prop: "pric"},
        {name: "开单科室", prop: "deptId", op: 'deptOptions'},
        {name: "开单医生", prop: "createName"},
        {name: "执行科室", prop: "deptId", op: 'deptOptions'},
        {name: "数据来源", prop: "dataSource"},
        {name: "减免金额", prop: "derateMoney"},],
      tableRows2: [
        {name: "药品名称", prop: "drugName"},
        {name: "规格描述", prop: "drugSpec"},
        {name: "单位剂量", prop: "unitDose"},
        {name: "剂量单位", prop: "dosUnt", op: 'dosaUntOptions'},
        {name: "数量", prop: "cnt"},
        {name: "给药方式", prop: "medcWayId", op: 'medicationFrequencyOptions'},
        {name: "成本", prop: "purcPric"},
        {name: "单价", prop: "salePric"},
        {name: "金额", prop: "saleAmt"},],
      tableRows3: [
        {name: "药品名称", prop: "drugName"},
        {name: "付数", prop: "tcmCnt"},
        {name: "单位", prop: "unt", op: 'dosaUntOptions'},
        {name: "剂量单位", prop: "sdoseUnt", op: 'dosaUntOptions'},
        {name: "数量", prop: "cnt"},
        {name: "给药方式", prop: "medcWayId", op: 'medicationFrequencyOptions'},
        {name: "成本", prop: "purcPric"},
        {name: "单价", prop: "salePric"},
        {name: "金额", prop: "saleAmt"},
        {name: "医保编码", prop: "chsCode"},
        {name: "医保名称", prop: "chsName"}],
      tableRows4: [
        {name: "健康ID", prop: "id"},
        {name: "健康卡号", prop: "patId"},
        {name: "姓名", prop: "name"},
        {name: "身份证号", prop: "certno"},
        {name: "联系电话", prop: "conerTel"},
      ],
      tableRows5: [
        {name: "就诊序号", prop: "seeDoctor"},
        {name: "姓名", prop: "patientName"},
        {name: "性别", prop: "gender",op:'sexOptions'},
        {name: "就诊时间", prop: "createTime"},
        {name: "执行金额", prop: "pric"},
        {name: "开单科室", prop: "deptId",op:'deptOptions'},
        {name: "开单医生", prop: "createName"},
        {name: "西医诊断", prop: "westernDiagnos"},
        {name: "中医诊断", prop: "chinaDiagnose"},
      ],
      tableRows6: [
        {name: "项目名称", prop: "content"},
        {name: "执行单价", prop: "pric"},
        {name: "执行金额", prop: "pric"},
        {name: "开单医生", prop: "createName"},
        {name: "开单科室", prop: "deptId",op:'deptOptions'},
        {name: "执行科室", prop: "deptId",op:'deptOptions'},
      ],
      tableRows7: [
         {name: "姓名", prop: "name"},
        {name: "健康ID", prop: "patNo"}, {name: "性别", prop: "sex", op: 'sexOptions'},
        {name: "挂号类型", prop: "regTypeId", op: 'regOptions'},
        {name: "挂号方式", prop: "regMode", op: 'regModeOption'},
        {name: "应收金额", prop: "receivedMoney"}, {name: "实收金额", prop: "receivableMoney"},
        {name: "现金支付", prop: "cashAmt"}, {name: "网络支付", prop: "groupAmt"}, {name: "支付方式", prop: "payType", op: 'payTypeOptions'},
      ],
      tableRows8: [
         {name: "姓名", prop: "patName"},
        {name: "健康ID", prop: "patCode"}, {name: "性别", prop: "sex", op: 'sexOptions'},
        {name: "病人费别", prop: "patCostType"},
        {name: "应收金额", prop: "receAmt"},
        {name: "现金支付", prop: "cashAmt"},
        {name: "网络支付", prop: "groupAmt"},
        {name: "医保支付", prop: "chsAmt"},
        {name: "收费时间", prop: "feeTime"},
      ],

      finalReportShowFrom: {
        clinicName: '',
        staffName: '',
        timeRange: [
          dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss'), // 开始时间
          dayjs().format('YYYY-MM-DD HH:mm:ss') // 结束时间
        ]
      },
      defaultTimeRange: [
        dayjs().startOf('year').toDate(), // 转换为 Date 对象
        dayjs().toDate() // 转换为 Date 对象
      ],

      //表单
      addUnitForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },//合约单位新增修改表单
      addOnCreditForm: {
        beginTime: '',
        code: '',
        cotUnit: null,
        endTime: '',
        name: '',
        pycode: '',
        remarks: '',
        state: 1,
      },//挂账类型新增修改表单
      patientChooseForm: {
        id: null,
        patId: '',
        name: '',
        sex: null,
        certno: null,
        conerTel: null,
        contractUnit: null,
        healthCardNo: null,
        cardType: null,
      },//选择患者表单
      outpatientChargesForm: {
        id: null,
        patId: null,
        name: null,
        age: null,
        billingDoctor: null,
        billingDept: null,
        remainingSum: null,
        chargeItem: null,
        specification: null,
        executeDept: null,
        price: null,
        amount: null,
        patientType: null,
        ticketType: 1,
        currentTicketNo: null,
        currentTotal: null,
        discountedTotal: null,
        BeforePatId: '',
        BeforePaidAmt: null,
        BeforeReceiveAmt: null,
        BeforeChange: null,
      },//表格头表单
      paymentForm: {
        age: null,
        aliAmt: null,
        bankAmt: null,
        bebtAmt: null,
        bebtId: null,
        bebtType: '',
        bilgDepId: null,
        bilgDepName: '',
        bilgDrId: null,
        bilgDrName: '',
        cashAmt: null,
        chsAmt: null,
        distAmt: null,
        groupAmt: null,
        invoNo: '',
        opeWay: null,
        paidAmt: null,
        patAmt: null,
        patCostType: null,
        patId: null,
        patName: '',
        patType: null,
        recdAmt: null,
        receAmt: null,
        regId: null,
        remarks: '',
        seeId: null,
        sex: null,
        shHarId: null,
        wechatAmt: null,
        balance: null,
        observation: null,
        observationAdvance: null,
        change: null,
        ids: [],
        clientId: '',
      },//门诊收费结算表单
      patientForm: {
        id: null,
        patId: '',       // 健康ID
        thrNot: false,   // 三无（复选框应为布尔值）
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: null,        // 年龄-岁
        ageMonth: null,       // 年龄-月
        naty: '汉族',     // 民族
        jobId: null,            // 职业
        feeType: null, // 病员费别
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        isSpecial: '否',    // 特殊人群
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        registerDate: new Date().toISOString().split('T')[0],   // 挂号日期
        timeSlot: '1',       // 时段
        department: null,     // 科室
        doctor: null,         // 医生
        registerType: null,   // 挂号类别
        clinicRoom: null,  // 诊室
        existNumber: null,
        currentNumber: null,
        caseHistory: null,
        total: null,
        naplAddCode: null,
        conerAddCode: null,
        number: null,
      },//患者信息表单
      //新增健康档案表单
      celerityFilingForm: {
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: 0,        // 年龄-岁
        ageMonth: 0,       // 年龄-月
        ageDay: 0,       // 年龄-天
        naty: 1,     // 民族
        ntlyId: 1,    //国籍
        jobId: '',            // 职业
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        tel: null,
        restAddCode: null,
        naplAddCode: null,
      },


      //表单验证
      addOnCreditFormRules: {
        code: [
          {required: true, message: '请输入编码', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur'}
        ],

        beginTime: [
          {required: true, message: '请选择开始时间', trigger: 'change'}
        ],
        endTime: [
          {required: true, message: '请选择结束时间', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (this.addOnCreditForm.beginTime && value) {
                if (new Date(value) < new Date(this.addOnCreditForm.beginTime)) {
                  callback(new Error('结束时间不能早于开始时间'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }, //挂账
      addUnitRules: {
        code: [{required: true, message: '请填写合约单位编码！', trigger: 'change'}],
        name: [{required: true, message: '请填写合约单位名称！', trigger: 'change'}],
      },//合约单位
      addForm: {
        discountMoney: null,
        name: '',
        patientId: null,
        payType: null,
        receivableMoney: null,
        receivedMoney: null,
        regDepId: null,
        regDoctorId: null,
        regMode: null,
        regNum: null,
        regTypeId: null,
        regUserId: null,
        remake: '',
        utyTimeDetailsId: null,
        visitId: null,
        rgstId: null,
        /**/
        accountNumber: null,
        currentNumber: null,
        oweNumber: '0/0',
        remark: null,
        feeType: null,
        MoneyPay: null,
        healthCarePay: null,
        fitnessCardpa: null,
        unionPay: null,
        owePay: null,
        phonePay: null,
        discountsNumb: null,
        receivableNum: null,
        receiveNumber: null,
        changeNumber: null,
      },
      userInfo: null,
      permissionsArr:[],
      unitStateOption: [{id: 1, label: '启用'}, {id: 0, label: '禁用'}],
      areaOption: [{id: 1, label: '省内'}, {id: 2, label: '省外'}, {id: 3, label: '进口'}],
    };
  },
  beforeDestroy() {
    // 组件销毁时移除监听，避免内存泄漏
    window.removeEventListener('keydown', this.handleKeyPress);
  },
  mounted() {
    this.addUnitType = AddType.map(function (v) {
      return v
    })
    window.addEventListener('keydown', this.handleKeyPress);
    this.terminalId = parseInt(localStorage.getItem('terminalId'));
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
    this.getArea();
    this.getDoctorList();
    this.getDeptList();
    this.loadData();
    this.dict();
    this.getSqbPaymentState();
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {
    async getRegisterType() {
      if (this.regOptions.length > 0) return;
      const res = await getRegisterType();
      this.regOptions = res.data.map(item => {
        return {label: item.designation, id: item.id}
      })
    },
    async handleChargeListSizeChange(val){
      this.pageSize = val;
      this.pageNum = 1;
      await this.getChargeList();
    },
    async handleChargeListCurrentChange(val){
      this.pageNum = val;
      await this.getChargeList();
    },

    async handleRegistrationSizeChange(val){
      this.pageSize = val;
      this.pageNum = 1;
      await this.getReservationList();
    },
    async handleRegistrationCurrentChange(val){
      this.pageNum = val;
      await this.getReservationList();
    },

    async getChargeList(){
      const res = await getChargeList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        startTime: this.finalReportShowFrom.timeRange[0],
        endTime: this.finalReportShowFrom.timeRange[1],
      });
      if (res.code === 200) {
        this.tableData7 = res.data.content
            .map(item => ({
              ...item,
              feeTime: item.feeTime === null ? null : dayjs(item.feeTime).format('YYYY-MM-DD HH:mm:ss'),
            }))
        this.totalSize = res.data.totalSize;
      }
    },
    async getReservationList() {
      const newItem = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        startTime: this.finalReportShowFrom.timeRange?.[0] || '',
        endTime: this.finalReportShowFrom.timeRange?.[1] || '',
      }
      let res = await getAllReservation(newItem);
      if (res.code === 200) {
        this.totalSize = res.data.totalSize;
        this.tableData6 = res.data.content.map(item => {
          return {
            ...item,
            payType: parseInt(item.payType)
          }
        });
      } else {
        this.$message.error(res.message)
      }
    },
    handleTabClick(tab) {
      switch(tab.name) {
        case 'classInfo':
          break
        case 'paymentInfo':
          this.activeTab = 'paymentInfo'
          this.getChargeList();
          break
        case 'registrationInfo':
          this.activeTab = 'registrationInfo'
          this.getRegisterType();
          this.getReservationList()
          break
      }
    },
    handleOpenFinalReport(){
      this.finalReportShowFrom.clinicName = this.userInfo.clinicName;
      this.finalReportShowFrom.staffName = this.userInfo.staffName;
      this.finalReportDialogVisible = true;
    },
    handleCloseFinalReport() {
      this.finalReportForm = Object.assign({}, this.$options.data.call(this).finalReportForm);
      this.finalReportDialogVisible = false;
    },
    handleSaveContractUnit() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = true;
    },
    handleCancelAddUnit() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = false;
    },
    async getOutPatientCharge(row){
      this.outpatientChargesForm.patId = row.cardId === '' ? row.patientName : row.cardId;
      await new Promise(resolve => setTimeout(resolve, 1000));
      await this.handleSearch(row);
      this.awaitingPayDialogVisible = false;
    },
    async getAwaitPayDetail(row, event){
      await withLoading(this, '数据处理中...')(async () => {
        const res = await getChargelist({patientId:row.patientId,status: 1});
        if (res.code === 200){
          this.showAwaitingPayDetail = true;
          this.tableData5 = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    async loadData() {
      await withLoading(this, '加载中...')(async () => {
        const res = await getChargelist({status: 1});
        if (res.code === 200) {
          const merged = {};
          res.data.forEach(item => {
            if (!merged[item.seeDoctor]) {
              merged[item.seeDoctor] = {...item};
            } else {
              merged[item.seeDoctor].pric = (+merged[item.seeDoctor].pric || 0) + (+item.pric || 0);
            }
          });

          this.tableData4 = Object.values(merged);
          this.awaitingPayDialogVisible = true;
        }
      });
    },


    handleKeyPress(event) {
      // 检查是否为 F9 键（兼容 key 和 keyCode）
      if (event.key === 'F9' || event.keyCode === 120) {
        event.preventDefault(); // 阻止默认行为
        this.handleIdCardData(); // 调用你的业务方法
      }
    },
    async handleIdCardData() {
      try {
        await withLoading(this, '身份证读取中...')(async () => {
          const res = await readIdCard();
          this.outpatientChargesForm.patId = res.cardno;
          await this.handleSearch()
        });
      } catch (error) {
        this.$message.error(error)
      } finally {

      }
    },

    async getSqbPaymentState() {
      const res = await getSqbPaymentState({orderId: this.orderId});
      console.log(res, 'const res = await getSqbPaymentState({ orderId: this.orderId });')
    },


    resetScanner() {
      this.scanStatus = 'waiting';
      this.paymentCode = '';
      this.countdown = 5;
      this.errorMessage = '付款失败，请重试';
      clearInterval(this.timer);
      cancelAnimationFrame(this.animationFrameId);
      this.$nextTick(() => {
        const input = this.$refs.paymentCodeInput?.$el?.querySelector('input');
        if (input) {
          input.focus();
          input.select();
        }
      });
    },

    handlePayDialogOpened() {
      this.resetScanner();
      this.$nextTick(() => {
        const input = this.$refs.paymentCodeInput;
        if (input) {
          // 双重聚焦确保Element UI组件接受焦点
          input.focus();
          input.$el.querySelector('input').focus();

          // 防止意外失去焦点（扫码枪场景专用）
          this._blurHandler = () => {
            setTimeout(() => input.$el.querySelector('input').focus(), 10);
          };
          input.$el.querySelector('input').addEventListener('blur', this._blurHandler);
        }
      });
    },

    handlePayDialogClosed() {
      this.resetScanner();
      if (this._blurHandler) {
        this.$refs.paymentCodeInput?.$el
            .querySelector('input')
            .removeEventListener('blur', this._blurHandler);
      }
    },


    handleScanComplete(val) {
      clearTimeout(this.scanTimer);
      this.scanTimer = setTimeout(() => {
        val = val.trim();
        if (!val) return;

        // 验证格式
        const isAlipay = /^(25|26|27|28|29|30)\d{14,22}$/.test(val);
        const isWechat = /^(10|11|12|13|14|15)\d{16}$/.test(val);

        if (!isAlipay && !isWechat) {
          this.$message.error('付款码格式错误');
          this.errorMessage = '付款码格式错误';
          this.scanStatus = 'error';
          this.paymentCode = '';
          this.startCountdown();
          return;
        }

        // 开始处理
        this.processPayment(val);
      }, 300);
    },

    //qwe
    async processPayment(code) {
      this.scanStatus = 'processing';

      try {
        const res1 = await sqbPayment({dynamicId: code, orderId: this.orderId});

        // 处理支付结果
        if (res1.data === 'PAY_SUCCESS') {
          this.scanStatus = 'success';
          // 支付成功
          this.startCountdown();
        } else if (res1.data === 'PAY_IN_PROGRESS') {
          this.scanStatus = 'processing';
          // 支付中，开始轮询
          await this.pollPaymentStatus(20); // 最多轮询20次
        } else if (res1.data === 'PAY_ERROR') {
          this.scanStatus = 'error';
          // 支付失败
          this.handlePaymentError();
        }

      } catch (error) {
        // 网络或系统错误
        this.handlePaymentError();
      }
    },
    async pollPaymentStatus(maxAttempts) {
      let attempts = 0;
      const pollInterval = 2000; // 2秒轮询一次

      const poll = async () => {
        attempts++;

        try {
          const res = await getSqbPaymentState({orderId: this.orderId});

          if (res.data === 'PAY_SUCCESS') {
            // 轮询期间支付成功了
            this.scanStatus = 'success';
            this.startCountdown();
          } else if (res.data === 'PAY_ERROR' || attempts >= maxAttempts) {
            // 支付失败或达到最大轮询次数
            this.scanStatus = 'error';
            this.handlePaymentError();
          } else {
            // 继续轮询
            if (attempts < maxAttempts) {
              setTimeout(poll, pollInterval);
            }
          }

        } catch (error) {
          // 查询出错也视为失败
          this.handlePaymentError();
        }
      };

      // 开始轮询
      await poll();
    },

    handlePaymentError() {
      this.scanStatus = 'error';
      this.startCountdown();
      this.$message.error('支付处理失败');
    },

    startCountdown() {
      // 清除现有动画帧和定时器
      cancelAnimationFrame(this.animationFrameId);
      clearInterval(this.countdownInterval);

      // 初始化倒计时
      this.countdown = 5;
      this.countdownStartTime = Date.now();

      // 启动动画帧循环
      const animate = () => {
        const elapsed = Date.now() - this.countdownStartTime;
        const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));

        // 更新显示
        this.countdown = remaining;

        if (remaining > 0) {
          // 继续下一帧
          this.animationFrameId = requestAnimationFrame(animate);
        } else {
          // 倒计时结束
          if (this.scanStatus === 'success') {
            this.handleBeforeCharge();
          }
          this.resetScanner();
        }
      };

      this.animationFrameId = requestAnimationFrame(animate);
    },


    //挂账类型修改模态框回显
    async handleOpenEditOnCredit(item) {
      const res = await getOnCreditById({id: item.id});

      const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = new Date(timestamp.toString().length === 10 ? timestamp * 1000 : timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      };

      this.addOnCreditForm = {
        ...res.data,
        beginTime: formatTime(res.data.beginTime),
        endTime: formatTime(res.data.endTime)
      };
      await this.getContuntList();
      this.addOnCreditDialogVisible = true;
    },

    //挂账类型新增模态框处理
    handleOpenAddOnCredit() {
      this.getContuntList();
      this.addOnCreditDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.addOnCreditForm.clearValidate();
      });
    },

    //清空挂账类型数据
    handleCloseAddOnCredit() {
      this.addOnCreditForm = {};
      this.addOnCreditForm.state = 1;
      this.addOnCreditDialogVisible = false;
    },

    //挂账类型名称转拼音
    handleOnCreditNameGetPy() {
      this.addOnCreditForm.pycode =
          pinyin(this.addOnCreditForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
    },

    //新增修改挂账类型
    async handleAddOnCredit() {
      try {
        // 验证表单
        const valid = await this.$refs.addOnCreditForm.validate();
        if (!valid) {
          this.$message.warning('请完善表单信息');
          return false;
        }

        let res;
        // 判断是新增还是编辑
        if (this.addOnCreditForm.id) {
          // 有id -> 编辑操作
          res = await editOnCredit(this.addOnCreditForm);
        } else {
          // 无id -> 新增操作
          res = await addOnCredit(this.addOnCreditForm);
        }

        // 统一处理响应
        if (res.code === 200) {
          this.addOnCreditDialogVisible = false;
          this.handleCloseAddOnCredit();
          await this.getOnCreditList();
          this.onCreditDialogVisible = true;
        } else {
          this.$message.error(res.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请重试');
      }
    },

    //挂账类型下拉框
    async getOnCreditList() {
      const res = await getOnCreditList()
      this.onCreditOption = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    handleBeforeCharge() {
      const BeforePatId = this.outpatientChargesForm.patId;
      const BeforePaidAmt = this.paymentForm.paidAmt;
      const BeforeReceiveAmt = this.paymentForm.paidAmt;
      const BeforeChange = this.paymentForm.change;
      this.handleCancelCurrentPatient();
      this.outpatientChargesForm = {
        BeforePatId: BeforePatId,
        BeforePaidAmt: BeforePaidAmt,
        BeforeReceiveAmt: BeforeReceiveAmt,
        BeforeChange: BeforeChange
      };
      this.paymentCode = '';
      this.orderId = null;
      this.settleAccountsDialogVisible = false;
      this.onCreditDialogVisible = false;
      this.payModalVisible = false;
    },


    async handleCashCharge() {
      console.log(this.tableData1,'this.tableData1this.tableData1this.tableData1')
      this.paymentForm.bilgDrId = this.tableData1[0].createId;
      this.paymentForm.ids = this.tableData1.map(item => item.id);
      this.paymentForm.opeWay = this.paymentForm.groupAmt > 0 ? 1 : 0;
      this.paymentForm.patId = this.patientChooseForm.id;
      this.paymentForm.patName = this.outpatientChargesForm.name;
      this.paymentForm.seeId = this.tableData1[0].seeDoctor;
      this.paymentForm.age = this.outpatientChargesForm.age;
      this.paymentForm.bilgDepId = this.userInfo.selDept;
      this.paymentForm.bilgDepName = this.deptOptions.find(item => item.id === this.userInfo.selDept)?.label ?? null;
      this.paymentForm.bilgDrName = this.userInfo.staffName;
      this.paymentForm.patCostType = this.outpatientChargesForm.patientType;
      this.paymentForm.regId = this.tableData1[0].registerId;
      this.paymentForm.sex = this.patientChooseForm.sex;
      this.paymentForm.clientId = this.terminalId;

      try {
        const res = await addConfirmPayment(this.paymentForm);
        if (res.code === 200) {
          if (this.paymentForm.opeWay === 1) {
            this.payModalVisible = true;
            this.orderId = res.data;
            return;
          }
          this.handleBeforeCharge();
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        this.$message.error("系统异常:请联系管理员!!!");
      } finally {

      }
    },

    handleClosePayment() {
      this.paymentForm = Object.assign({}, this.$options.data.call(this).paymentForm);
      this.settleAccountsDialogVisible = false;
    },

    //门诊收费确认结算
    async handleConfirmPayment() {
      try {
        await withLoading(this, '支付中...')(async () => {
          console.log(this.paymentForm.bebtAmt)
          console.log(this.paymentForm.cashAmt)
          console.log(this.paymentForm.groupAmt)
          // 1. 验证挂账金额是否导致现金支付为负
          if (Number(this.paymentForm.bebtAmt) > Number(this.paymentForm.currentTotal)) {
            return this.$message.warning("挂账金额不能超过应收金额");
          }

          // 2. 处理挂账情况
          if (this.paymentForm.bebtAmt > 0) {
            await this.getOnCreditList();
            this.onCreditDialogVisible = true;
            return;
          }

          // 3. 处理现金支付（需验证是否足额支付）
          /*if (Number(this.paymentForm.cashAmt) <= 0) {
            return this.$message.warning("请确认支付金额");
          }*/

          if (Math.abs(Number(this.paymentForm.cashAmt) - Number(this.paymentForm.recdAmt)) < 0.01) {
            await this.handleCashCharge();
          } else {
            this.$message.warning("实收金额与应收金额不匹配");
          }
        });
      } catch (error) {
        this.$message.error("系统异常:请联系管理员")
      } finally {

      }


      /*console.log(this.paymentForm,'this.paymentFormthis.paymentFormthis.paymentFormthis.paymentForm')
      this.payModalVisible = true;*/
    },

    handleCloseOnCredit() {
      this.paymentForm.bebtId = null;
      this.$message.warning("请选择挂账类型!!!");
      this.onCreditDialogVisible = false;
    },

    //确认选择挂账类型
    handleConfirmPayment2() {
      this.paymentForm.bebtType = this.onCreditOption.find(item => item.id === this.paymentForm.bebtId).label;
      this.handleCashCharge();
    },

    //结算模态框 计算各种金额
    calculatePayments() {
      // ========== 新增：正则过滤所有金额字段 ==========
      const validateAmount = (value) => {
        const num = Number(value);
        // 允许空值或非负数
        return value === '' || (!isNaN(num) && num >= 0);
      };

      // 校验所有支付金额字段
      const amountFields = [
        this.outpatientChargesForm.currentTotal, // 应收金额
        this.paymentForm.chsAmt,    // 医保
        this.paymentForm.bankAmt,   // 银联
        this.paymentForm.bebtAmt,   // 挂账
        this.paymentForm.groupAmt,  // 网络
        this.paymentForm.patAmt     // 健康卡
      ];

      if (!amountFields.every(validateAmount)) {
        this.$message.warning('请输入有效的正数金额');
        return; // 如果校验失败，终止计算
      }

      // ========== 原计算逻辑 ==========
      // 1. 获取应收金额（已通过校验，可直接转换）
      const total = Number(this.outpatientChargesForm.currentTotal) || 0;

      // 2. 计算非现金支付总额（已通过校验，可直接转换）
      const nonCashPaid = [
        this.paymentForm.chsAmt,
        this.paymentForm.bankAmt,
        this.paymentForm.bebtAmt,
        this.paymentForm.groupAmt,
        this.paymentForm.patAmt
      ].reduce((sum, val) => sum + (Number(val) || 0), 0);

      // 3. 计算现金支付缺口
      const cashGap = total - nonCashPaid;

      this.paymentForm = {
        ...this.paymentForm,
        cashAmt: cashGap.toFixed(2),      // 需现金支付金额
        recdAmt: Math.max(0, cashGap).toFixed(2), // 实际收到现金（避免负数）
        change: cashGap < 0 ? Math.abs(cashGap).toFixed(2) : 0.00, // 找零金额（正数）
        paidAmt: (nonCashPaid + Math.max(0, cashGap) - (this.paymentForm.bebtAmt ? Number(this.paymentForm.bebtAmt) : 0)).toFixed(2)
      };
    },

    //打开结算模态框
    handleSettleAccounts() {
      if (this.outpatientChargesForm.patId === null || this.outpatientChargesForm.currentTotal === null) {
        this.$message.warning("请选择指定患者")
        return;
      }

      this.settleAccountsDialogVisible = true;
      this.paymentForm.cashAmt = this.outpatientChargesForm.currentTotal;
      this.calculatePayments();
      this.$nextTick(() => {
        // 找到 ref="recdAmt" 的输入框并聚焦
        if (this.$refs.recdAmt) {
          this.$refs.recdAmt.focus();
        }
      });
    },

    //单位剂量 最小剂量下拉框
    async getDosaUnt() {
      const res = await getDosaUnt();
      this.dosaUntOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    //给药方式下拉框
    async getMedicationFrequency() {
      const res = await getMedicationFrequency();
      this.medicationFrequencyOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    //表格合计列计算
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'purcPric': '成本',
        'salePric': '单价',
        'saleAmt': '金额',
        'cnt': '数量'
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'pric': '执行金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },

    //修改按钮
    handleEditCurrentCharge() {
      this.$message.warning('抱歉,非手工加入的项目不允许收费室修改');
    },

    //重置页面数据
    handleCancelCurrentPatient() {
      this.outpatientChargesForm = Object.assign({}, this.$options.data.call(this).outpatientChargesForm)
      this.paymentForm = Object.assign({}, this.$options.data.call(this).paymentForm);
      this.tableData1 = [];
      this.tableData2 = [];
      this.tableData3 = [];
    },

    //移除表格某一行处方信息
    handleCancelCurrentRow() {
      if (!this.currentRowData) return;

      // 过滤掉与当前行匹配的数据
      this.tableData1 = this.tableData1.filter(item =>
          item !== this.currentRowData
      );

      // 清空当前选中行
      this.currentRowData = null;
      this.outpatientChargesForm.currentTotal = parseFloat(this.tableData1.reduce((sum, item) => sum + (Number(item.pric) || 0), 0).toFixed(2));
      this.outpatientChargesForm.discountedTotal = parseFloat(this.tableData1.reduce((sum, item) => sum + (Number(item.pric) || 0), 0).toFixed(2));
    },

    //左表格数据单击事件
    async handleCurrentRow(row) {
      this.currentRowData = row;
      if (row.orderType === 0) {
        await this.getDosaUnt();
        await this.getMedicationFrequency();
        const res = await getWestDetail(row.orderTypeId)
        console.log(res, 'resresresresresresresresresresresresresresresres')
        this.tableData2 = res.data.drxDetails;
        this.hasInitTable0 = true;
        this.showDetails = true;
        return;
      }
      if (row.orderType === 1) {
        await this.getDosaUnt();
        await this.getMedicationFrequency();
        const res = await getChinaDetail({id: row.orderTypeId})
        console.log(res, 'resresresresresresresresresresresresresresresres')
        this.tableData3 = res.data.tcmDetailsRespVOS;
        this.hasInitTable1 = true;
        this.showDetails = true;
        return;
      }
      this.tableData2 = [];
      this.tableData3 = [];
      this.$nextTick(() => {
        this.$refs.rightTable?.doLayout();
      });
    },

    //项目价格下拉框
    async getChargingPrice() {
      if (this.chargingPriceOptions.length > 0) return;
      const res = await getChargingPrice();
      this.chargingPriceOptions = res.data.map(item => {
        return {
          id: item.id, label: item.costname, odcost: item.odcost,
          executedepid: item.executedepid, depexecutetype: item.depexecutetype
        }
      })
    },

    //医生下拉框
    async getDoctorList() {
      if (this.doctorOptions.length > 0) return;
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, fullName: item.fullName}
      })
    },

    //根据身份证生日
    certnoMonitor(val) {
      if (!val.certno) return;

      const idCard18Reg = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      if (!idCard18Reg.test(val.certno)) {
        this.$message.error("身份证格式不正确");
      }

      const data = this.getAgeAndMonthsFromIdCard(val.certno);
      val.ageYear = data.years;
      val.ageMonth = data.months;
      val.brdy = val.certno.slice(6, 10) + '-' +
          val.certno.slice(10, 12) + '-' +
          val.certno.slice(12, 14)
    },

    //根据身份证出生日期
    getAgeAndMonthsFromIdCard(idCard) {
      if (!idCard || idCard.length !== 18) return {years: 0, months: 0, birthday: ''};

      const birthStr = idCard.slice(6, 14); // 格式：YYYYMMDD
      const birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;

      const birthDate = new Date(birthday);
      if (isNaN(birthDate.getTime())) return {
        years: 0,
        months: 0,
        birthday: ''
      };

      // 2. 获取当前日期
      const today = new Date();

      // 3. 计算周岁
      let years = today.getFullYear() - birthDate.getFullYear();

      // 4. 计算月龄（总月数差）
      let months = (today.getFullYear() - birthDate.getFullYear()) * 12 +
          (today.getMonth() - birthDate.getMonth());

      // 5. 调整年龄和月龄（如果生日未到）
      if (
          today.getMonth() < birthDate.getMonth() ||
          (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
      ) {
        years--;
        months--;
      }

      // 6. 确保月龄为正数
      months = Math.max(0, months % 12); // 超过12个月的部分已计入周岁

      return {years, months, birthday};
    },

    //快速建档新增
    async handleAddCelerityFiling() {
      this.celerityFilingForm.tel = this.celerityFilingForm.conerTel;
      this.celerityFilingForm.restAddCode = this.handleAddressChangeCode(this.celerityFilingForm)
      this.celerityFilingForm.naplAddCode = this.handleAddressChangeCode(this.celerityFilingForm)
      console.log(this.celerityFilingForm)
      const res = await addDocphr(this.celerityFilingForm);
      if (res.code === 200) {
        this.celerityFilingDialogVisible = false;
      } else {
        this.$message.error(res.message)
      }

    },

    //转换城市代码
    handleAddressChangeCode(form) {
      const {province, city, county, town, village} = form;

      // 从村级开始逐级向上检查
      if (village && village.trim() !== '') {
        return village; // 返回村级代码
      }
      if (town && town.trim() !== '') {
        return town; // 返回乡级代码
      }
      if (county && county.trim() !== '') {
        return county; // 返回县级代码
      }
      if (city && city.trim() !== '') {
        return city; // 返回市级代码
      }
      return province || ''; // 默认返回省级（即使为空）
    },

    //科室下拉框
    async getDeptList() {
      if (this.deptOptions.length > 0) return;
      const res = await getDeptList();
      this.deptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
    },

    //合约单位名称转拼音
    handleNameChangeCode(v, i) {
      switch (i) {
        case 1 :
          this.addUnitForm.pyCode =
              pinyin(this.addUnitForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
      }
    },

    //新增修改合约单位
    async handleAddContractUnit() {
      if (this.addUnitForm.id) {
        const res = await editContractUnit(this.addUnitForm);
        if (res.code === 200) {
          await this.getContuntList();
          this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
          this.addUnitModalVisible = false;
        } else {
          this.$message.error("系统异常:修改合约单位失败!")
        }
      } else {
        const res = await addContractUnit(this.addUnitForm);
        if (res.code === 200) {
          await this.getContuntList();
          this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
          this.addUnitModalVisible = false;
        } else {
          this.$message.error("系统异常:添加合约单位失败!")
        }
      }

    },

    //合约单位模态框清理
    handleCancelContract() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = false;
    },

    //修改合约单位
    async handleEditContractUnit(item) {
      const res = await getContractUnit(item.id.toString())
      this.addUnitForm = res.data
      this.addUnitModalVisible = true;
    },

    //患者选择表格存储选中行对象
    handleClickRow(row) {
      this.patientChooseForm = row;
    },

    //查找患者处方
    async handleChoosePatient() {
      await withLoading(this, '加载中...')(async () => {
        const res = await getChargelist({patientId: this.patientChooseForm.id, status: 1})
        if (!res.data || res.data.length === 0) {
          try {
            await MessageBox.alert('没有找到该患者的处方收费信息', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            });
          } finally {
            this.handleCancelCurrentPatient();
          }
          return;
        }
        this.outpatientChargesForm.name = this.patientChooseForm.name;
        this.outpatientChargesForm.age = this.getAgeAndMonthsFromIdCard(this.patientChooseForm.certno).years;
        this.outpatientChargesForm.patId = this.patientChooseForm.patId;
        this.outpatientChargesForm.patientType = this.patientChooseForm.prhType;
        this.outpatientChargesForm.amount = 1;
        this.outpatientChargesForm.billingDept = res.data[0].deptId;
        this.outpatientChargesForm.billingDoctor = res.data[0].createName;
        //this.outpatientChargesForm.executeDept = westObj[0].deptId;
        this.outpatientChargesForm.currentTotal = parseFloat(res.data.reduce((sum, item) => sum + (Number(item.pric) || 0), 0).toFixed(2));
        this.outpatientChargesForm.discountedTotal = parseFloat(res.data.reduce((sum, item) => sum + (Number(item.pric) || 0), 0).toFixed(2));
        this.tableData1 = res.data.map(item => {
          return {
            ...item,
            dataSource: '医嘱',
            derateMoney: 0
          }
        })
        console.log(this.tableData1, 'this.tableData1this.tableData1this.tableData1this.tableData1')
        this.patientDialogVisible = false;
      });
    },

    //患者搜索
    async handleSearch(row) {
      console.log(row,'rowrowrowrow')
      await withLoading(this, '加载中...')(async () => {
        this.patientFormDisabled = true;
        const res = await getDocphrList({condtion: this.outpatientChargesForm.patId});
        if (res.data.length > 1) {
          this.patientDialogVisible = true;
          this.patientTableData = res.data;
          return;
        } else if (res.data.length <= 0) {
          this.$message.warning("没有搜索到相关患者!请在健康档案新增或点击下方快速建档!")
          this.patientFormDisabled = false;
          return;
        }
        this.patientChooseForm = res.data[0];
        await this.handleChoosePatient()
        this.patientFormDisabled = false;
      });
    },

    //数据字典
    async dict() {
      const res = await dict();
      this.nationOption = res.data.natyEntities.map(item => {
        return {id: item.id, label: item.name}
      })
      this.certypeOption = res.data.certypeEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.profttlOption = res.data.profttlEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.prhCostOption = res.data.prhCostType.map(item => {
        return {id: item.id, label: item.name}
      })

      this.prhTypeOption = res.data.prhType.map(item => {
        return {id: item.id, label: item.name}
      })

      this.rltsEntitiesOption = res.data.rltsEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.untAtteOption = res.data.unatteVo.map(item => {
        return {id: item.id, label: item.name}
      })

      this.ntlyOptions = res.data.country.map(item => {
        return {id: item.id, label: item.name}
      })

      this.chinaMakeOptions = res.data.methodTypeVO.map(item => {
        return {id: item.id, label: item.name}
      })

      this.tcmwayOptions = res.data.tcmway.map(item => {
        return {id: item.id, label: item.name}
      })
    },

    //递级清理地域数据, 如(清空市数据,则会清空市下面所有下拉框数据(县-镇-村-乡))
    handleClear(res) {
      switch (res) {
        case 1:
          this.patientForm.province = ''
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          this.profttlOption = [];
          break;

        case 2:
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          break;
        case 3:
          this.patientForm.county = '';
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          break;

        case 4:
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          break;

        case 5:
          this.patientForm.village = '';
          this.villageOption = [];
          break;
      }
    },

    //合约单位下拉框
    async getContuntList() {
      const res = await getContuntList();
      this.contractUnitOption = res.data.map(item => {
        return {id: item.id, label: item.name}
      })
    },

    //获取村
    async getVillage() {
      const areaCode = this.patientForm.town === '' ? this.celerityFilingForm.town : this.patientForm.town;
      const res = await getArea({areaCode: areaCode, areaLevel: 5, condtion: 'area_t_code'})
      this.villageOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取镇
    async getTown() {
      this.patientForm.village = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.county === '' ? this.celerityFilingForm.county : this.patientForm.county;
      const res = await getArea({areaCode: areaCode, areaLevel: 4, condtion: 'area_d_code'})
      this.townOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取县
    async getCounty() {
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.city === '' ? this.celerityFilingForm.city : this.patientForm.city;
      const res = await getArea({areaCode: areaCode, areaLevel: 3, condtion: 'area_c_code'})
      this.countyOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取市
    async getCity() {
      this.patientForm.county = ''
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.county = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.province === '' ? this.celerityFilingForm.province : this.patientForm.province;
      const res = await getArea({areaCode: areaCode, areaLevel: 2, condtion: 'area_p_code'})
      this.cityOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取省
    async getArea() {
      this.patientForm.city = ''
      this.patientForm.county = ''
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.city = ''
      this.celerityFilingForm.county = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const res = await getArea();
      this.provinces = res.data.map(item => {
        return {id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel}
      })
    },

    //自动计算宽度
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 100; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串


      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 8; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 12;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },

    //表格数据回显
    safeGetMappedValue(col, row) {
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 80;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
  }
}
</script>


<style lang="less" scoped>
/* 地址选择器容器样式 */
.address-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

/* 地址单位标签样式 */
.address-unit {
  margin: 0 5px;
  color: #909399;
  font-size: 12px;
}

/* 紧凑表单样式 */
.compact-form .el-form-item {
  margin-bottom: 12px;
}

.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); /* 半透明遮罩 */
}

.el-icon-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.payment-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.form-header {
  background: #409EFF;
  color: white;
  padding: 10px 15px;
  margin: -20px -20px 20px -20px;
  border-radius: 4px 4px 0 0;
  font-size: 16px;
  font-weight: bold;
}

.form-section {
  background: white;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.payment-summary {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 15px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  display: inline-block;
  width: 120px;
  text-align: left;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}


.el-table__footer-wrapper {
  position: sticky !important;
  bottom: 0;
  background: white;
  z-index: 10;
  display: table-footer-group !important;
}

/* 调整滚动区域 */
.el-table__body-wrapper {
  max-height: calc(55vh - 48px) !important;
  overflow-y: auto !important;
}

.custom-summary-table {
  overflow: visible !important;
}

/* 将合计行固定在表格数据下方（不受滚动条影响） */
.custom-summary-table .el-table__footer-wrapper {
  position: sticky !important;
  bottom: 0;
  background: white;
  z-index: 10;
  border-top: 1px solid #ebeef5; /* 可选：添加分隔线 */
}

/* 调整表格内滚动区域高度 */
.custom-summary-table .el-table__body-wrapper {
  max-height: calc(55vh - 48px); /* 减去合计行高度 */
  overflow-y: auto !important;
}

/* 全局样式或组件内样式 */
.el-table__footer {
  background-color: white !important; /* 改为白色背景 */
  border-top: 1px solid #EBEEF5; /* 保留顶部边框线 */
}

.el-table__footer .el-table__cell {
  background-color: inherit !important; /* 继承白色背景 */
}

/* 调整文字样式（可选） */
.el-table__footer .cell {
  color: #606266; /* 默认文字颜色 */
  font-weight: normal; /* 取消加粗 */
}

.medical-system-container {
  display: flex;
  flex-direction: column;
  height: 65vh;
  width: 100%;
  overflow: hidden;
  position: relative;
}

/* 主表格区域 */
.table-main-container {
  display: flex;
  flex: 1;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

/* 左表格 - 默认铺满 */
.table-left {
  flex: 1;
  height: 100%;
  overflow: auto;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 右抽屉表格 - 初始隐藏 */
.table-drawer {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 0;
  background: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  z-index: 10;
  overflow: hidden;
}

/* 抽屉打开状态 */
.table-drawer.open {
  width: 40%; /* 可根据需要调整宽度 */
  min-width: 400px; /* 最小宽度 */
}

.drawer-content {
  height: 100%;
  width: 100%;
  overflow: auto;
  box-sizing: border-box;
}

/* 当抽屉打开时，左表格缩进 */
.table-main-container.with-drawer .table-left {
  margin-right: 40%; /* 与抽屉宽度一致 */
}

/* 底部控制表单 - 固定在底部 */
.bottom-control-form {
  padding: 10px;
  background: #f5f7fa;
  border-top: 1px solid #e6e6e6;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
}

.form-grid {
  display: flex;
  flex-direction: column;
}


/* 按钮组布局 */
.button-group {
  display: flex;
  justify-content: space-between;
}

.primary-actions {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 表格样式增强 */
.el-table {
  height: 100%;
}

.el-table th {
  background-color: #f8f8f9;
  font-weight: 600;
}

.el-table--border {
  border: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .table-drawer.open {
    width: 50%;
    min-width: 350px;
  }

  .table-main-container.with-drawer .table-left {
    margin-right: 50%;
  }
}

.form-grid {
  display: flex;
  flex-direction: column;
}

.form-main {
  margin-bottom: 70px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}

.primary-actions,
.action-buttons {
  display: flex;
  gap: 8px;
}


.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px; /* 按钮间距 */
}


/* 新增底部输入盒子样式 */
.bottom-input-box {
  padding: 15px;
  background: #f8f8f9;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}


/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

.dialog {
  .addUnitDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }

  .patient-dialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}


/* Vue 2 深度选择器写法 */
.custom-table /deep/ .el-table--border {
  border: 1px solid #e6e6e6;
}

.custom-table /deep/ .el-table__header th,
.custom-table /deep/ .el-table__body td {
  border-right: 1px solid #e6e6e6;
  border-bottom: 1px solid #e6e6e6;
}

.custom-table /deep/ .el-table__header th {
  background-color: #f5f7fa; /* 表头背景色 */
}

.data-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 70px;
  font-size: 13px;
}

.el-input {
  flex: 1;
}


.side-panel {
  width: 240px;
  padding: 10px;
  background: #f5f7fa;
}

.registration-box {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.data-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  width: 70px;
  font-size: 13px;
  color: #ffffff;
  margin-right: 4px;
}

.el-input {
  flex: 1;
}

.el-input.is-disabled .el-input__inner {
  background-color: #f5f5f5;
  color: #666;
}

/* 新增样式 */
.register-group {
  width: 50%;
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

/* 调整原有分隔线位置 */
.divider-line {
  width: 100%;
  margin: 12px 0 8px;
}

/* 强制同行显示 */
.register-type + .clinic-room {
  margin-left: -8px; /* 补偿间距 */
}

/* 关键修复样式 */
.compact-form {
  /* 在原有样式基础上添加 */

  .register-type,
  .clinic-room {
    flex: 1; /* 平分剩余空间 */
    min-width: 240px; /* 最小宽度保证换行后对齐 */
    max-width: 50%; /* 最大不超过50% */

    /deep/ .el-form-item__content {
      width: calc(100% - 90px) !important; /* 匹配label宽度 */
    }
  }

  /* 强制同行显示 */

  .register-type + .clinic-room {
    margin-left: -8px; /* 补偿间距 */
  }

  /deep/ .el-form-item__content {
    margin-left: 0 !important; /* 消除ElementUI默认的左侧间距 */
    width: auto !important; /* 取消固定宽度 */
  }

  /deep/ .el-form-item__label {
    padding-right: 6px !important; /* 标签与输入框间距 */
    width: auto !important; /* 取消标签固定宽度 */
    flex: none !important; /* 禁用flex自动分配 */
  }

  .el-form-item {
    /* 调整整体间距 */
    gap: 4px; /* 标签与控件间距 */
    margin-bottom: 15px;
    /* 微调对齐方式 */
    align-items: baseline;
  }

  /* 特殊处理复选框 */

  .el-checkbox {
    margin-left: 2px;

    /deep/ .el-checkbox__label {
      display: none; /* 隐藏默认标签 */
    }
  }

  /* 输入框尺寸补偿 */

  .el-input--mini {
    line-height: 28px;

    /deep/ .el-input__inner {
      padding: 0 8px;
    }
  }
}

.compact-form-box {
  height: auto !important; /* 改为自适应高度 */
  padding: 12px 8px; /* 调整内边距 */
}

.compact-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px; /* 行列间距 */

  .el-form-item {
    margin: 0;
    display: inline-flex;
    align-items: center;

    /* 标签对齐 */

    /deep/ .el-form-item__label {
      line-height: 28px;
      padding-right: 4px;
    }

    /* 表单控件通用样式 */

    .el-input,
    .el-select,
    .el-date-editor {
      width: 100px; /* 默认宽度 */
    }

    /* 特定字段宽度调整 */

    &[label="性别:"] .el-select {
      width: 70px;
    }


    &[label="职业:"] .el-select {
      width: 130px;
    }

    &[label="病员费别:"] .el-select,
    &[label="病员类型:"] .el-select {
      width: 135px;
    }

    &[label="联系电话:"] .el-input {
      width: 135px;
    }


    &[label="挂号类别:"] .el-select,
    &[label="诊室:"] .el-select {
      width: 300px;
    }

    /* 地址输入组 */

    .age-select-address {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-input {
        width: 60px !important;

        &:nth-last-child(2) {
          width: 150px !important;
        }

        /* 乡镇输入框 */
      }
    }
  }

  /* 分隔线样式 */

  .divider-line {
    width: 100%;
    margin: 20px 10px 0;
    border-top: 1px solid #ebeef5;
  }
}


.divider-line {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 10px 0;
}

.compact-form-box {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 6px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.compact-form {
  font-size: 12px;
}

.el-form-item {
  margin-bottom: 5px;
}

.age-unit {
  margin: 0 5px;
  color: #ffffff;
  font-size: 12px;
}

.MedicenCata {
  height: 100%;
  width: 100%;

  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    .header-icon {
      width: 100%;
      display: flex;
      align-items: center;
    }
  }

}
</style>